package com.wuyan.web.base.config;

import com.wuyan.web.base.entity.PubConfig;
import com.wuyan.web.base.helper.BaseApi;
import com.wuyan.web.base.helper.PubConfigHelper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Target;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Map;


/**
 * Feign调用的时候添加请求头
 *
 * @author wuyan
 */

@Slf4j
@Configuration
public class FeignConfig implements RequestInterceptor {

    @Autowired
    private BaseApi baseApi;

    @Autowired
    private PubConfigHelper configHelper;

    @SneakyThrows
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (null == attributes) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();

        /*
            保证每次请求均携带认证信息
         */
        String accessToken = baseApi.getAccessToken(request);
        if (StringUtils.isNotBlank(accessToken)) {
            Map<String, Collection<String>> headers = requestTemplate.headers();
            if (headers.containsKey("authorization") || headers.containsKey("Authorization")) {
                return;
            }
            requestTemplate.header("authorization", accessToken);
        }

        List<PubConfig> configs = configHelper.configs("service", "domain-name");
        Target<?> target = requestTemplate.feignTarget();
        String name = target.name();
        for (PubConfig config : configs) {
            if (name.equals(config.getCfgValue())) {

            }
        }
    }
}
